package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.app.func.MyWindowFunction;
import com.atguigu.bean.TrafficIsNewBean;
import com.atguigu.bean.TrafficIsNewBean;
import com.atguigu.bean.TrafficIsNewBean;
import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.MyClickHouseUtil;
import com.atguigu.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import java.time.Duration;

public class Dws0103TrafficIsNewWindow {
    public static void main(String[] args) throws Exception {
        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
//        tableEnv.getConfig().setIdleStateRetention(Duration.ofSeconds(18*60+5));
        //  状态后端设置
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");
        //2.从kafka DWD读取dwd_traffic_page_view的数据
        DataStreamSource<String> kafkaDS = env.fromSource(MyKafkaUtil.getKafkaSource("dwd_traffic_page_view", "traffic_source"), WatermarkStrategy.<String>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<String>() {
            @Override
            public long extractTimestamp(String s, long l) {
                JSONObject jsonObject = JSON.parseObject(s);
                return jsonObject.getLong("ts");
            }
        }), "kafka-source");
        //3.将数据转换为JSONOBJECT
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(JSON::parseObject);
        //4.按照Mid Keyby,并将数据转换为JavaBean
        SingleOutputStreamOperator<TrafficIsNewBean> keyByWithMidDS = jsonObjDS.keyBy(r->r.getJSONObject("common").getString("mid")).map(new RichMapFunction<JSONObject, TrafficIsNewBean>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build();
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("mid-state", String.class);
                stateDescriptor.enableTimeToLive(ttlConfig);
                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public TrafficIsNewBean map(JSONObject jsonObject) throws Exception {
                //获取状态
                String lastDt = valueState.value();
                Long ts = jsonObject.getLong("ts");
                String curDt = DateFormatUtil.toYmdHms(ts);
                long midCount = 0L;
                if (lastDt == null || !lastDt.equals(curDt)) {
                    midCount = 1L;
                    valueState.update(curDt);

                }
                JSONObject page = jsonObject.getJSONObject("page");
                JSONObject common = jsonObject.getJSONObject("common");
                String isNew = "";
                if ("0".equals(common.getString("is_new"))){
                    isNew = "老用户";
                }else {
                    isNew = "新用户";
                }



                return TrafficIsNewBean.builder()
                        .midCount(midCount)
                        .pageCount(1L)
                        .durSum(page.getLong("during_time"))
                        .sid(common.getString("sid"))
                        .isNew(isNew)
                        .ts(ts)
                        .build();
            }
        });
        keyByWithMidDS.print("keyByWithMidDS>>>>");
        //5.按照sid keyBy,补充会话总数
        SingleOutputStreamOperator<TrafficIsNewBean> keyByWithSidDS = keyByWithMidDS.keyBy(TrafficIsNewBean::getSid).map(new RichMapFunction<TrafficIsNewBean, TrafficIsNewBean>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build();
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("mid-state", String.class);
                stateDescriptor.enableTimeToLive(ttlConfig);
                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public TrafficIsNewBean map(TrafficIsNewBean trafficIsNewBean) throws Exception {
                String lastDt = valueState.value();
                Long ts = trafficIsNewBean.getTs();
                String curDt = DateFormatUtil.toYmdHms(ts);
                long sidCount = 0L;
                if (lastDt == null || !lastDt.equals(curDt)) {
                    valueState.update(curDt);
                    sidCount = 1L;
                }

                return com.atguigu.bean.TrafficIsNewBean.builder()
                        .midCount(trafficIsNewBean.getMidCount())
                        .pageCount(1L)
                        .durSum(trafficIsNewBean.getDurSum())
                        .sidCount(sidCount)
                        .ts(ts)
                        .isNew(trafficIsNewBean.getIsNew())
                        .ts(trafficIsNewBean.getTs())
                        .build();
            }
        });
        keyByWithSidDS.print("keyByWithSidDS>>>>");
        //6.分组 开窗 聚合
        SingleOutputStreamOperator<TrafficIsNewBean> reduceDS = keyByWithSidDS.keyBy(TrafficIsNewBean::getIsNew).window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10))).reduce(new ReduceFunction<TrafficIsNewBean>() {
            @Override
            public TrafficIsNewBean reduce(TrafficIsNewBean value1, TrafficIsNewBean value2) throws Exception {
                value1.setMidCount(value1.getMidCount() + value2.getMidCount());
                value1.setSidCount(value1.getSidCount() + value2.getSidCount());
                value1.setPageCount(value1.getPageCount() + value2.getPageCount());
                value1.setDurSum(value1.getDurSum() + value2.getDurSum());
                return value1;
            }
        }, new MyWindowFunction<String, TimeWindow, TrafficIsNewBean>());
        reduceDS.print("reduceDS>>>>");
        //7.写出
        reduceDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_traffic_isnew_window values (?,?,?,?,?,?,?,?)"));
        env.execute();



    }
}
